// @flow
import React from 'react'
import styles from './DeviceTypeSettings.css'
import { Button, Popconfirm } from 'antd'
import DevicePartModal from 'components/DevicePartModal'
// import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { getDeviceType } from 'utils/GeneralOptions'

type Props = {
  history: Object,
  data: Object,
  refreshView: Function,
  deleteDevice: Function,
  api: Object
}
type States = {
  addLoading: boolean,
  addDevice: boolean,
  deviceSorts: Array<Object>,
  parentId: string
}
export default class DeviceTypeSettings extends React.Component {
  props: Props
  state: States
  toEdit: Function
  openAddDeviceModal: Function
  closeAddDeviceModal: Function
  handleDelete: Function
  addPoint: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      addLoading: false,
      addDevice: false,
      deviceSorts: [],
      parentId: ''
    }
    this.toEdit = this.toEdit.bind(this)
    this.openAddDeviceModal = this.openAddDeviceModal.bind(this)
    this.closeAddDeviceModal = this.closeAddDeviceModal.bind(this)
    this.handleDelete = this.handleDelete.bind(this)
    this.addPoint = this.addPoint.bind(this)
  }
  addPoint () {
    const { history, data } = this.props
    history.push({
      pathname: '/business/device-point-add',
      state: {
        data: data
      }
    })
  }

  toEdit () {
    const { history, data } = this.props
    history.push({
      pathname: '/business/device-type-edit',
      state: {
        data: data,
        recordId: data.id
      }
    })
  }

  handleDelete () {
    const { data, deleteDevice } = this.props
    deleteDevice(data)
  }
  openAddDeviceModal () {
    const { data } = this.props

    getDeviceType((json) => {
      this.setState({
        deviceSorts: json.result,
        addDevice: true,
        parentId: data.id
      })
    })
  }

  closeAddDeviceModal () {
    this.setState({
      addDevice: false
    })
  }
  render () {
    const { data } = this.props
    const { addDevice, parentId, deviceSorts } = this.state
    return (
      <div className={styles['buttons']}>
        {
          data.parentId === 0
          ? <Button size='small'
            type='primary'
            onClick={this.addPoint}
            >添加测点</Button>
          : false
        }
        <Button size='small'
          type='primary'
          onClick={this.toEdit}
          >编辑</Button>
        <Popconfirm title='确定要删除此设备吗'
          onConfirm={this.handleDelete}
          >
          <Button size='small' type='danger'
            >删除</Button>
        </Popconfirm>
        <Button size='small' type='primary'
          onClick={this.openAddDeviceModal}
          >添加部件</Button>
        <DevicePartModal
          {...{
            visible: addDevice,
            parentId,
            deviceSorts,
            refreshView: this.props.refreshView,
            closeModal: this.closeAddDeviceModal
          }}
          />
      </div>
    )
  }
}
